<template>
  <div class="question-space-container">
    <div class="question-space">
      <!-- 返回按钮和标题 -->
      <div class="header">
        <div class="back-button" @click="handleBack">
          <i class="el-icon-arrow-left"></i>
        </div>
        <h1 class="title" style="background-color: transparent;">提问</h1>
      </div>

      <!-- 提问表单 -->
      <div class="ask-form">
        <!-- 标题输入 -->
        <div class="input-section">
          <el-input
              v-model="questionTitle"
              type="textarea"
              :maxlength="42"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入问题标题"
              show-word-limit
          ></el-input>
        </div>

        <!-- 添加发布者输入框 -->
        <div class="input-section">
          <el-input
              v-model="publisher"
              placeholder="请输入您的名称"
              maxlength="50"
          >
            <template slot="prepend">发布者</template>
          </el-input>
        </div>

        <!-- 添加联系方式输入框 -->
        <div class="input-section">
          <el-input
              v-model="phone"
              placeholder="请输入您的联系方式"
              maxlength="20"
          >
            <template slot="prepend">联系方式</template>
          </el-input>
        </div>

        <!-- 问题描述 -->
        <div class="input-section">
          <el-input
              v-model="questionDescription"
              type="textarea"
              :maxlength="1000"
              :autosize="{ minRows: 4, maxRows: 8 }"
              placeholder="请输入问题描述"
              show-word-limit
          ></el-input>
        </div>

        <!-- 图片上传，保持原有的界面 -->
        <div class="image-upload-section">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="9"
              :file-list="imageList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-change="handleChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>

        <!-- 发布按钮 -->
        <div class="submit-section">
          <el-button
              type="primary"
              round
              :disabled="!isValidForm"
              @click="submitQuestion"
          >
            立即发布
          </el-button>
        </div>
      </div>
    </div>

    <!-- 退出确认对话框 -->
    <el-dialog
        title="提示"
        :visible.sync="showExitDialog"
        width="30%"
        center
    >
      <span>退出编辑，内容将会丢失</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="continueEditing">继续编辑</el-button>
        <el-button type="primary" @click="confirmExit">确认退出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sendRequest } from '@/util/request';

export default {
  name: 'QuesAsk',
  data() {
    return {
      questionTitle: '',
      questionDescription: '',
      imageList: [],
      showExitDialog: false,
      publisher: '', // 添加发布者字段
      phone: '',     // 添加联系方式字段
      loading: false,
      userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
    };
  },
  computed: {
    isValidForm() {
      return this.questionTitle.length > 0 &&
          this.questionTitle.length <= 42 &&
          this.questionDescription.length > 0 &&
          this.questionDescription.length <= 1000 &&
          this.publisher.length > 0 &&
          this.phone.length > 0;
    }
  },
  methods: {
    async uploadImage(file) {
      const formData = new FormData();
      formData.append('multipartFile', file);

      try {
        const res = await sendRequest('post', '/fileUpload', formData);
        console.log('上传响应:', res); // 调试用

        // 适配实际的响应结构（注意code是字符串"200"）
        if (res.code === "200" || res.code === 200) {
          // 直接从响应中获取url，而不是从data对象
          if (res.url) {
            console.log('获取到URL:', res.url);
            return res.url;
          }
        }
        console.error('上传响应格式不符:', res);
        throw new Error('上传失败: 未找到图片URL');
      } catch (error) {
        console.error('图片上传错误:', error);
        throw error;
      }
    },

    // 处理所有图片上传并将URL添加到描述中
    async uploadAllImages() {
      try {
        console.log('开始上传图片，共计:', this.imageList.length);

        // 逐个上传图片，而不是用Promise.all，这样可以看出是哪张出了问题
        const urls = [];
        for (const file of this.imageList) {
          try {
            const url = await this.uploadImage(file.raw);
            console.log('单张图片上传成功:', url);
            if (url) {
              urls.push(url);
            }
          } catch (err) {
            console.error(`上传图片 ${file.name} 失败:`, err);
            // 继续上传其他图片
          }
        }

        // 检查是否有成功上传的图片
        if (urls.length === 0) {
          throw new Error('没有图片上传成功');
        }

        console.log('成功上传的图片URLs:', urls);

        // 构建HTML
        const imageUrlsHtml = urls.map(url =>
            `<img src="${url}" style="max-width:100%;" />`
        ).join('\n');

        // 更新描述
        let finalDescription = this.questionDescription;
        if (finalDescription.trim()) {
          finalDescription += '\n\n' + imageUrlsHtml;
        } else {
          finalDescription = imageUrlsHtml;
        }

        return finalDescription;
      } catch (error) {
        console.error('图片上传过程错误:', error);
        this.$message.error('图片上传失败: ' + error.message);
        throw error;
      }
    },

    async submitQuestion() {
      if (!this.isValidForm) {
        return;
      }

      this.loading = true;
      try {
        // 如果有图片，先上传图片并将URL添加到描述中
        let finalDescription = this.questionDescription;
        if (this.imageList.length > 0) {
          try {
            finalDescription = await this.uploadAllImages();
          } catch (imageError) {
            console.error('图片处理错误:', imageError);
            this.$message.error('图片上传失败，请重试');
            this.loading = false;
            return;
          }
        }

        // 构建问题数据 - 使用表单中填写的值
        const questionData = {
          title: this.questionTitle,
          description: finalDescription,
          publisher: this.publisher,  // 使用用户填写的发布者
          phone: this.phone,          // 使用用户填写的联系方式
          isHidden: 0,
          isTop: 0
        };

        console.log('提交问题数据:', questionData);

        const res = await sendRequest('post', '/ques/add', questionData);
        if (res.code === 200 || res.code === "200") {
          this.$message.success('发布成功');
          this.$router.push('/ques/list');
        } else {
          this.$message.error(res.msg || '发表失败，请重试');
        }
      } catch (error) {
        console.error('提交问题失败:', error);
        this.$message.error('发表失败，请重试');
      } finally {
        this.loading = false;
      }
    },

    // 图片上传前的验证
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5; // 限制5MB

      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB！');
        return false;
      }
      return true;
    },

    // 其他方法保持不变
    handleBack() {
      if (this.questionTitle || this.questionDescription || this.imageList.length > 0) {
        this.showExitDialog = true;
      } else {
        this.$router.push('/ques/list');
      }
    },

    handleExceed() {
      this.$message.warning('最多只能上传9张图片');
    },

    handleRemove(file, fileList) {
      this.imageList = fileList;
    },

    handleChange(file, fileList) {
      this.imageList = fileList;
    },

    continueEditing() {
      this.showExitDialog = false;
    },

    confirmExit() {
      this.showExitDialog = false;
      this.$router.push('/ques/list');
    }
  }
};
</script>

<style scoped>
/* 输入框前缀样式 */
.el-input-group__prepend {
  background-color: #f5f5f5;
  color: #606266;
  min-width: 80px;
  text-align: center;
}

/* 让输入框在小屏幕上也有好的显示效果 */
@media (max-width: 768px) {
  .input-section .el-input-group {
    width: 100%;
  }
}
.question-space-container {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.question-space {
  position: relative;
  width: 33.33%;
  height: 100vh;
  background-color: #fff;
  background-image: url('E:/zhizhiniao1-ui/bird1-ui/src/assets/re_8640_userlmn_566c912f88a7.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: transparent;
  z-index: 20;
  text-align: center;
}

.back-button {
  position: absolute;
  left: 15px;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.title {
  width: 100%;
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  background-color: transparent;
}

.ask-form {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-section {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
}

.image-upload-section {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
}

/* Element UI 上传组件样式覆盖 */
:deep(.el-upload--picture-card) {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 输入框样式 */
:deep(.el-textarea__inner) {
  background-color: transparent;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

/* 提交按钮样式 */
.submit-section {
  margin-top: auto;
  padding: 20px 0;
  text-align: center;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
  border-radius: 30px;
  padding: 12px 24px;
  font-size: 16px;
  width: 200px;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.5);
}

.el-button--primary i {
  margin-right: 5px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .question-space {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .question-space {
    width: 95%;
  }
}

/* 对话框样式 */
:deep(.el-dialog) {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 30px 20px;
  text-align: center;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  text-align: center;
}
</style>
